﻿<script type="text/javascript" language="javascript">

    //called with something like this:
    //onclick="AZUREWCF_getAzureData('DataPage.aspx', 'myMethod', '', 
        //AZUREWCF_azureProcessResults, AZUREWCF_azureErrorProcessing);" />

    //div where the results will be displayed by default
    var AZUREWCF_RENDER_DIV = "AZUREWCF_azureDefaultDataRenderDiv";

    //div in the response that contains the WCF call results
    var AZUREWCF_DATA_RESULTS_DIV = "##RESULTDIV##";

	//div in the response that shows server where the request was executed
	var AZUREWCF_SERVERNAME_DIV = "##SERVERNAME_DIV##";

	//div where the server name will be displayed
	var AZUREWCF_SERVERNAME_RESULTS_DIV = "AZUREWCF_azureServerNameRenderDiv";

	//div in the response that any error message that was returned
	var AZUREWCF_ERRORMSG_DIV = "##ERRORMSG_DIV##";

	//div where the error message will be displayed
	var AZUREWCF_ERRORMSG_RESULTS_DIV = "AZUREWCF_azureErrorMessageRenderDiv";

	//div in the response with the trace info
	var AZUREWCF_TRACEINFO_DIV = "##TRACEINFO_DIV##";

	//div where the trace info will be displayed
	var AZUREWCF_TRACEINFO_RESULTS_DIV = "AZUREWCF_azureTraceInfoRenderDiv";

	//debug flag
	var AZUREWCF_DEBUG_FLAG_RESULTS_DIV = "AZUREWCF_azureDebugFlagDiv";


    function AZUREWCF_getAzureData(pageName, methodName, methodParams, successCallback, errorCallback, divID) 
    {
        try 
        {
			//get the render div and set the contents to the twirling gears; that way if someone
			//is entering this through the Refresh button they know that the button click
			//has been processed
			var targetElement = document.getElementById(AZUREWCF_RENDER_DIV + divID);
			targetElement.innerHTML = "<img src='/_layouts/images/GEARS_AN.GIF'/>";

            //call the page with the query strings that were passed in
            $.ajax({
                type: "GET",  
                url: pageName,
                cache: ##CACHE_OPTION##, 
				context: targetElement, 
				contents: divID, 
                dataType: "text",
                data: "##QS_METHOD##=" + methodName + "&##QS_PARAMS##=" + methodParams + "&##QS_OUTPUT##=page&##QS_DECODE##=##DECODE_VAL##&##QS_ACCESSDENIED##=##AD_VALUE##&##QS_TIMEOUT##=##TIMEOUT_VALUE##",
                dataFilter: AZUREWCF_azureFilterResults,
                success: successCallback, 
                error: errorCallback
                });
        }
        catch (ex) 
        {          
            alert("An error occurred processing your request: " + ex.description);
        }
    }


    function AZUREWCF_azureFilterResults(resultData, dataType) 
    {
        //return value
        var rawData = "";

        try 
        {
			//get the raw results data to display and/or return
			rawData = AZUREWCF_azureGetDataSubset(AZUREWCF_DATA_RESULTS_DIV, resultData);

			//figure out the unique ID for the calling web part so that the correct
			//debug info divs are updated
			var baseID = $(this).get(0).contents;

			//see if there's any content; if it's zero length then most likely it's because
			//the Url to the page was incorrect
			if (rawData.length == 0)
			{
				//get the debug div to see if debug info is turned on
				var debugDiv = document.getElementById(AZUREWCF_DEBUG_FLAG_RESULTS_DIV + baseID);
				
				//get the raw url and try to trim out to the first question mark
				var rawUrl = $(this).get(0).url;
				var qMark = rawUrl.indexOf("?");
				var sourceUrl;

				if (qMark > -1)
					sourceUrl = rawUrl.substr(0, qMark);
				else
					sourceUrl = rawUrl;

				if (debugDiv.innerHTML == "1")
					alert("No data was returned; make sure the Data Page property " + 
					sourceUrl + " is a valid Url.");
			}

			//server name	
			var serverNameDiv = document.getElementById(AZUREWCF_SERVERNAME_RESULTS_DIV + baseID);
			serverNameDiv.innerHTML = AZUREWCF_azureGetDataSubset(AZUREWCF_SERVERNAME_DIV, resultData);

			//error message
			var errMsgDiv = document.getElementById(AZUREWCF_ERRORMSG_RESULTS_DIV + baseID);
			errMsgDiv.innerHTML = "<font color='red'>" +
				AZUREWCF_azureGetDataSubset(AZUREWCF_ERRORMSG_DIV, resultData) + 
				"</font>";

			//trace info
			var traceInfoDiv = document.getElementById(AZUREWCF_TRACEINFO_RESULTS_DIV + baseID);
			traceInfoDiv.innerHTML = AZUREWCF_azureGetDataSubset(AZUREWCF_TRACEINFO_DIV, resultData);
        }
        catch (ex) 
        {
            //nothing for now
        }

        return rawData;
    }


	function AZUREWCF_azureGetDataSubset(tagName, resultData)
	{
		//return value
		var value = "";

		try
		{
			//find the data div in the results
			var startIndex, endIndex;
			startIndex = resultData.indexOf("<DIV id=\"" + tagName + "\">");
			endIndex = resultData.indexOf("</DIV>", startIndex);
			
			//get the length of the <div> opening tag so it can be removed from the results
			//11 is a constant that accounts for the characters <DIV id="">
			var tagLength = 11 + tagName.length;

			//extract the data out
			value = resultData.substr(startIndex + tagLength, endIndex - startIndex - tagLength);
		}
		catch (ex)
		{
			//nothing for now
		}

		return value;
	}


    function AZUREWCF_azureProcessResults(resultData, resultCode, queryObject) 
    {
        try 
        {
            //determine if there was an error or success
            if (resultCode == "error")
                alert("There was an error processing a request: " + resultData.responseText);  //statusText will just say "Not Found" or something like that
            else
            {
                //get the default div element added by the web part element to store results

                //NOTE:  IF YOUR METHOD RETURNS SCRIPT, THE SCRIPT TAG MUST INCLUDE THE 
                //DEFER ATTRIBUTE IN ORDER TO WORK PROPERLY WHEN ASSIGNING IT TO THE 
                //INNERHTML LIKE THIS, e.g. <script DEFER language='javascript'>

                //ALSO, IF YOU ARE ADDING OTHER FORMATTING TAGS, LIKE <STYLE>, YOU NEEED
                //TO WRAP THEM IN A <PRE> TAG OR THEY WILL NOT BE PROCESSED CORRECTLY, 
                //e.g. <Pre><Style>.foo {font-size:8pt;}</Style></Pre>
				$(this).get(0).innerHTML = resultData;
            }
        }
        catch (ex) 
        {
            alert("An error occurred processing your request: " + ex.description);
        }
    }


    function AZUREWCF_azureErrorProcessing(XMLHttpRequest, textStatus, errorThrown) 
    {
        try 
        {
           //get the target div and empty it out
           var targetElement = document.getElementById(AZUREWCF_RENDER_DIV);
           targetElement.innerHTML = "";

           //display error message
           alert("An error occurred processing a data request: " + textStatus);
        }
        catch (ex) 
        {
            alert("An error occurred handling an error with your request: " + ex.description);
        }
    }


	function toggleDebugDetailsDiv(imgName, divName)
    {
		var img = document.getElementById(imgName); 
        var div = document.getElementById(divName); 

		if ((img != null) && (div != null))
		{
			if (img.src.substr(img.src.length - 8) == 'plus.gif')
			{ 
				img.src = '/_layouts/images/minus.gif'; 
				div.style.display = 'block'; 
			} 
			else 
			{
				img.src = '/_layouts/images/plus.gif'; 
				div.style.display = 'none'; 
			} 
		}
    } 

</script>